﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace GmailMetroNotifier.Client.Common
{
    /// <summary>
    /// Represents a type-safe event handler implementing the weak-event pattern.
    /// </summary>
    /// <typeparam name="TSender">The type of the event sender argument.</typeparam>
    /// <typeparam name="TEventArgs">The type of the event arguments.</typeparam>
    [DebuggerNonUserCode]
    public sealed class WeakEventHandler<TSender, TEventArgs>
        where TSender : class
        where TEventArgs : class
    {
        private readonly WeakReference _targetReference;
        
        private readonly MethodInfo _method;

        /// <summary>
        /// Initializes a new instance of the class using the given callback.
        /// </summary>
        /// <param name="callback">The callback that will be called in response to the
        /// event.</param>
        /// <exception cref="ArgumentNullException">Thrown when the callback is null.</exception>
        public WeakEventHandler(EventHandler<TEventArgs> callback)
        {
            if (callback == null)
            {
                throw new ArgumentNullException("callback");
            }

            this._method = callback.Method;

            this._targetReference = new WeakReference(callback.Target, true);
        }

        /// <summary>
        /// Gets a weak handler suitable for an event with the specified
        /// sender type and arguments type.
        /// </summary>
        /// <param name="sender">The sender of the event.</param>
        /// <param name="e">The arguments of the event.</param>
        [DebuggerNonUserCode]
        public void Handler(TSender sender, TEventArgs e)
        {
            var target = _targetReference.Target;
            
            if (target != null)
            {
                Action<TSender, TEventArgs> callback = (Action<TSender, TEventArgs>)Delegate.CreateDelegate(typeof(Action<TSender, TEventArgs>), target, _method, true);
                
                if (callback != null)
                {
                    callback(sender, e);
                }
            }
        }
    }
}
